package com.jingdianjichi.gateway.exception;


import cn.dev33.satoken.exception.SaTokenException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jingdianjichi.gateway.entity.Result;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

public class GatewayExceptionHandler implements ErrorWebExceptionHandler {

    private ObjectMapper objectMapper = new ObjectMapper();


    @Override
    public Mono<Void> handle(ServerWebExchange serverWebExchange, Throwable throwable) {
        //获取上下文
        ServerHttpRequest request = serverWebExchange.getRequest();
        ServerHttpResponse response = serverWebExchange.getResponse();
        //处理异常
        Integer statusCode = null;
        String message = null;
        if (throwable instanceof SaTokenException) { //处理由satoken抛出的异常
            statusCode = 401;
            message="无此权限";
        }else {
            statusCode = 500;
            message = throwable.getMessage();
        }
        //封装结果
        Result result = Result.fail(statusCode, message);

        //解析回去
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);//添加请求头,返回json格式数据
        return response.writeWith(Mono.fromSupplier(() -> {
            DataBufferFactory dataBufferFactory = response.bufferFactory();// 获取响应数据缓冲区工厂
            byte[] bytes = null;
            try {
                bytes = objectMapper.writeValueAsBytes(result);// 将 Result 对象转为字节数组
            } catch (JsonProcessingException e) {
                e.printStackTrace();
                bytes = "{\"status\":500, \"message\":\"JSON转换错误\"}".getBytes();
            }
            // 使用缓冲区工厂将字节数组封装成 DataBuffer
            return dataBufferFactory.wrap(bytes);//dataBufferFactory.wrap()返回的是字节数据DataBuffer
        }));
    }
}


/*
@ControllerAdvice
@RestController
public class GatewayExceptionHandler {

    @ExceptionHandler(SaTokenException.class)
    public Mono<Result> handleSaTokenException(SaTokenException saTokenException) {
        Result result = Result.fail(401, "无此权限");
        return Mono.just(result);
    }

    @ExceptionHandler(Exception.class)
    public Mono<Result> handleGeneralException(Exception ex) {
        Result result = Result.fail(500, ex.getMessage());
        return Mono.just(result);
    }
}
*/




